package com.anlu.netty.chapter02.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * netty的客户端
 */
public class EchoClient {

    private final int port;
    private final String host;//主机名



    public EchoClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void start()throws InterruptedException{
        /**
         * 线程组
         */
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            //客户端启动必备
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)//指明使用nio进行网络通讯
            .remoteAddress(new InetSocketAddress(host,port))//配置远程服务器的地址
            .handler(new EchoClientHandler());
            //连接到远程节点，阻塞等到直到连接完成
            ChannelFuture channelFuture =b.connect().sync();
            //阻塞，直到channel关闭
            channelFuture.channel().closeFuture().sync();
        }finally {
            /**
             * 释放消息
             */
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws  InterruptedException{
        new EchoClient(9999, "127.0.0.1").start();
    }
}
